//
//  KKADManager.m
//  HybidMediation
//
//  Created by jay Win on 2019/9/17.
//  Copyright © 2019 jay Win. All rights reserved.
//

#import "KKADManager.h"
#import <KKAnalytics.h>
#import <SplashADManager.h>

@interface KKADManager()<KKAdsDelegate>
@property double initAdsTime;//初始化开始时间
@property double requestInterstitialStartTime;//请求插屏的开始时间
@property double requestRewardVideoStartTime;//请求激励视频的开始时间
@property int requestInterstitialTimes;//请求插屏的次数
@property int requestRewardVideoTimes;//请求激励的次数


@property BOOL debugModel;
@end

@interface KKADManager()<BUSplashAdDelegate>{
    
}
@end


@implementation KKADManager

+(instancetype)shareInstance{
    static KKADManager *manager=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [KKADManager new];
    });
    return manager;
}
#pragma mark  初始化
- (void)initAds:(BOOL)useLocalConfig debugModel:(BOOL)debug{
      _debugModel=debug;
     _initAdsTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
     [[KKAnalytics shareManager]logTKEvent:INIT_ADS params:nil];
    int selectedMediationType=_defalutMedationType;
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"AdsConfig.plist" ofType:nil];
    if(filePath==nil){
        NSLog(@"===============请确认已经添加AdsConfigp配置文件");
    }
    _adsConfig= [NSDictionary dictionaryWithContentsOfFile:filePath];
    if(useLocalConfig){
        if(_adsConfig==nil){
            NSLog(@"=============无效的AdsConfig配置文件");
            return;
        }
        NSString *selectMediationName=[_adsConfig objectForKey:@"MediationType"];
        
        if([_adsConfig objectForKey:@"CN"]&&[[[NSLocale currentLocale]objectForKey:NSLocaleIdentifier]hasSuffix:@"CN"]){
             selectedMediationType=-1;
             selectMediationName=@"ByteDance";
        }else{
            if([selectMediationName isEqualToString:@"Mopub"]){
                 selectedMediationType=1;
            }else if([selectMediationName isEqualToString:@"Max"]){
                 selectedMediationType=0;
            }
        }
        
        double duration=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970]-self->_initAdsTime;
        [[KKAnalytics shareManager]logTKEvent:LOAD_CONFIG params:@{MEDIATION_TYPE:selectMediationName,DURATION:@(duration),IS_LOCAL_CONFIG:@YES}];
        [self initMedation:selectedMediationType debugModel:debug];
    }else{
        if(_adsConfig==nil){
            NSLog(@"=============无效的AdsConfig配置文件");
            return;
        }
        NSString *configUrl=[_adsConfig objectForKey:@"AdsUrl"];
        if(configUrl==nil){
            NSLog(@"=============尚未配置网络广告配置地址，请在AdsConfig文件中进行配置，否则进行初始化本地配置");
            
            [self initAds:YES debugModel:debug];
            return;
        }
        NSURLSessionConfiguration *config=[NSURLSessionConfiguration defaultSessionConfiguration];
        config.timeoutIntervalForRequest=5;
        config.requestCachePolicy=NSURLRequestReloadIgnoringLocalCacheData;
        NSURLSession *session=[NSURLSession sessionWithConfiguration:config];
        NSURLSessionDataTask *dataTask=[session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:configUrl]]completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if(error){
                [[KKAnalytics shareManager]logTKEvent:LOAD_CONFIG_FAILED params:@{ERROR:error==nil?@"unKnow":error.localizedDescription}];
                 NSLog(@"================获取网络配置时发生错误%@,进行初始化本地配置",error.localizedDescription);
                [self initAds:YES debugModel:debug];
            }else{
                NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                [self showlog:[NSString stringWithFormat:@"远程配置的广告%@",[dic objectForKey:@"MediationType"]]];
                
                int  networkmediationType=self->_defalutMedationType;
                NSString *selectMediationName=[dic objectForKey:@"MediationType"];

                if([dic objectForKey:@"CN"]&&[[[NSLocale currentLocale]objectForKey:NSLocaleIdentifier]hasSuffix:@"CN"]){
                    networkmediationType=-1;
                    selectMediationName=@"ByteDance";
                }else{
                     if([selectMediationName isEqualToString:@"Mopub"]){
                               networkmediationType=1;
                     }else if([selectMediationName isEqualToString:@"Max"]){
                               networkmediationType=0;
                    }
                }
                double duration=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970]-self->_initAdsTime;
                [[KKAnalytics shareManager]logTKEvent:LOAD_CONFIG params:@{MEDIATION_TYPE:selectMediationName,DURATION:@(duration),IS_LOCAL_CONFIG:@NO}];
                [self initMedation:networkmediationType debugModel:debug];
            }
        }];
        [dataTask resume];
    }
}

- (void)initMedation:(int)medationType debugModel:(BOOL)debug{
     //todo 使用反射直接初始化对应的广告
    switch (medationType) {
        case -1:
            _baseController=[[ByteDanceAdsManager alloc]init];
            [self showlog:@"初始化中国地区头条广告"];
            break;
        case 1:
            _baseController=[[MopubAdMangaer alloc]init];
             [self showlog:@"初始化Mopub聚合广告"];
            break;
        case 0:
            //todo 使用反射直接初始化对应的广告
            _baseController=[[MaxAdManager alloc]init];
            [self showlog:@"初始化Max聚合广告"];
            break;
    }
    
    
    _baseController.debug=debug;
    if([[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]){
         _baseController.idfa=[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    }else{
        _baseController.idfa=@"";
    }
    if(_baseController.debug){
        [self showlog:[NSString stringWithFormat:@"广告id:%@",_baseController.idfa]];
    }
    _baseController.delegate=self;
    [self loadRequestSetting];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self->_baseController initAds:^{
            double initSuccedTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970]-self->_initAdsTime;
            [[KKAnalytics shareManager]logTKEvent:INIT_SUCCEED params:@{DURATION:@(initSuccedTime)}];
            [self.delegate onAdsListener:INIT_SUCCEED];
        }];
    });
}
-(void)loadRequestSetting{
    self.maxRecycleRequestInterstitialTimes=3;
    self.maxRecycleRequestRewardVideoTimes=3;

}


- (void)showlog:(NSObject *)obj{
    if(_debugModel)
    NSLog(@"===AD=====%@",obj);
}
- (void)onShowGdpr{
    [self showlog:@"需要展示GDPR授权面"];
    [self.delegate onAdsListener:NEED_SHOW_GDPR];
    [[KKAnalytics shareManager]logTKEvent:NEED_SHOW_GDPR params:nil];
}
- (void)agreeGDPR:(BOOL)status{
    [self showlog:@"GDPRs授权"];
    [[KKAnalytics shareManager]logTKEvent:AGREE_GDPR params:nil];
     if(_baseController&&status)
         [_baseController agreeGDPR];
}

- (void)agreeCOPPA:(BOOL)status{
        [self showlog:@"同意COPPA"];
        if(_baseController&&status)
               [_baseController agreeGDPR];
}

#pragma mark   开屏广告
- (void)loadSplash:(UIViewController *)rootViewController customView:(UIView *)logoView{
    [[SplashADManager shareInstance]loadSplash:rootViewController customView:logoView];
}
- (void)loadSplash:(UIViewController *)rootViewController customView:(UIView *)logoView onImpressionEvent:(NSString * _Nonnull (^)(void))onImpression onFailedEvent:(NSString * _Nonnull (^)(void))onFailed{
    [[SplashADManager shareInstance]loadSplash:rootViewController customView:logoView onImpressionEvent:onImpression onFailedEvent:onFailed];
}

#pragma mark   插屏
- (BOOL)hasInterstitial{
    return [_baseController hasInterstitial];
}
- (void)showInterstitial:(UIViewController *)rootViewController{
    if(_baseController)
        [_baseController showInterstitial:rootViewController];
}
- (void)showInterstitial:(UIViewController *)rootViewControoler onOpenEvent:(void (^)(void))onOpen onCloseEvent:(void (^)(void))onClose{
    if(_baseController)
        [_baseController showInterstitial:rootViewControoler onOpenEvent:onOpen onCloseEvent:onClose];
}
- (void)onInterstitialRequest {
     _requestInterstitialTimes++;
    [self showlog:[NSString stringWithFormat:@"第%d次请求插屏广告",_requestInterstitialTimes]];
    _requestInterstitialStartTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    [[KKAnalytics shareManager]logTKEvent:INTERSTITIAL_REQUEST params:@{LOAD_TIMES:@(_requestInterstitialTimes),RECYCLE_TIME:@(_currentlyRecycleRequestInterstitialTimes)}];
    [self.delegate onAdsListener:INTERSTITIAL_REQUEST];
}
- (void)onInterstitialLoaded {
    _currentlyRecycleRequestInterstitialTimes=0;
    [self showlog:[NSString stringWithFormat:@"插屏广告第%d次加载成功",_requestInterstitialTimes]];
    double loadTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970]-_requestInterstitialStartTime;
    [[KKAnalytics shareManager]logTKEvent:INTERSTITIAL_LOADED params:@{DURATION:@(loadTime),LOAD_TIMES:@(_requestInterstitialTimes),RECYCLE_TIME:@(_currentlyRecycleRequestInterstitialTimes)}];
    [self.delegate onAdsListener:INTERSTITIAL_LOADED];
}
- (void)onInterstitialLoadedFailed:(nonnull NSString *)error {
    if(_currentlyRecycleRequestInterstitialTimes==0){
        [self showlog:[NSString stringWithFormat:@"插屏首次加载失败，原因:%@将在3秒后开启循环加载，共循环%d轮",error,_maxRecycleRequestInterstitialTimes]];
    }else{
       [self showlog:[NSString stringWithFormat:@"插屏第%d循环加载失败",_currentlyRecycleRequestInterstitialTimes]];
     }
    [[KKAnalytics shareManager]logTKEvent:INTERSTITIAL_FAILED params:@{ERROR:error,LOAD_TIMES:@(_requestInterstitialTimes),RECYCLE_TIME:@(_currentlyRecycleRequestInterstitialTimes)}];
     _currentlyRecycleRequestInterstitialTimes++;
    [self.delegate onAdsListener:INTERSTITIAL_FAILED];
}
- (void)onInterstitialTrigger {
    [self showlog:@"插屏广告触发"];
    [[KKAnalytics shareManager]logTKEvent:INTERSTITIAL_SHOW params:nil];
}
- (void)onInterstitialPlayFailed:(nonnull NSString *)error {
    if(error){
         NSLog(@"插屏广告播放失败%@",error);
         [[KKAnalytics shareManager]logTKEvent:INTERSTITIAL_PLAY_ERROR params:@{ERROR:error,LOAD_TIMES:@(_requestInterstitialTimes)}];
    }
}
- (void)onInterstitialClick {
    [self showlog:@"插屏广告点击"];
    [[KKAnalytics shareManager]logTKEvent:INTERSTITIAL_CLICK params:nil];
    [self.delegate onAdsListener:INTERSTITIAL_CLICK];
}
- (void)onInterstitialOpen {
    [self showlog:@"插屏广告打开"];
    [[KKAnalytics shareManager]logTKEvent:INTERSTITIAL_OPEN params:nil];
     [self.delegate onAdsListener:INTERSTITIAL_OPEN];
}
- (void)onInterstitialClose {
    [self showlog:@"插屏广告关闭"];
    if([_adsConfig objectForKey:@"in_im"]){
        [[KKAnalytics shareManager]logAdjustEvent:[_adsConfig objectForKey:@"in_im"]];
    }else{
        NSLog(@"===== ADJUST ERROR================请在AdsConfig中设置in_im插屏展示打点Token");
    }
    [[KKAnalytics shareManager]logTKEvent:INTERSTITIAL_CLOSE params:nil];
    [self.delegate onAdsListener:INTERSTITIAL_CLOSE];
}


#pragma mark   激励
- (void)setRewardVideoAutoPlayWhenLoaded:(BOOL)autoPlay{
    _autoPlay=autoPlay;
}
- (BOOL)hasRewardVideo{
    return [_baseController hasRewardVideo];
}
- (void)showRewardVideo:(UIViewController *)rootViewController{
    if(rootViewController)
        _rootViewController=rootViewController;
    if(_baseController)
        [_baseController showRewardVideo:rootViewController];
}
- (void)showRewardVideo:(UIViewController *)rootViewController onOpenEvent:(void (^)(void))onOpen onCloseEvent:(void (^)(void))onClose onCompleteEvent:(void (^)(void))onComplete{
    if(rootViewController)
        _rootViewController=rootViewController;
    if(_baseController)
        [_baseController showRewardVideo:rootViewController onOpenEvent:onOpen onCloseEvent:onClose onCompleteEvent:onComplete];
}
- (void)onRewardVideoRequest {
    _requestRewardVideoTimes++;
    [self showlog:[NSString stringWithFormat:@"第%d次请求激励广告",_requestRewardVideoTimes]];
    _requestRewardVideoStartTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
    [[KKAnalytics shareManager]logTKEvent:REWARD_REQUEST params:@{LOAD_TIMES:@(_requestRewardVideoTimes),RECYCLE_TIME:@(_currentlyRecycleRequestRewardVideoTimes)}];
    [self.delegate onAdsListener:REWARD_REQUEST];
}
- (void)onRewardVideoLoaded {
    _currentlyRecycleRequestRewardVideoTimes=0;
    [self showlog:[NSString stringWithFormat:@"激励广告第%d次加载成功",_requestRewardVideoTimes]];
    double loadTime=[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970]-_requestRewardVideoStartTime;
    [[KKAnalytics shareManager]logTKEvent:REWARD_LOADED params:@{DURATION:@(loadTime),LOAD_TIMES:@(_requestRewardVideoTimes),RECYCLE_TIME:@(_currentlyRecycleRequestRewardVideoTimes)}];
    [self.delegate onAdsListener:REWARD_LOADED];
    if (self.autoPlay) {
        if(_rootViewController)
        [self showRewardVideo:_rootViewController];
        self.autoPlay=false;
    }
}

- (void)onRewardVideoLoadedFailed:(nonnull NSString *)error {
    if(_currentlyRecycleRequestRewardVideoTimes==0){
             [self showlog:[NSString stringWithFormat:@"激励首次加载失败，原因:%@将在3秒后开启循环加载，共循环%d轮",error,_maxRecycleRequestRewardVideoTimes]];
     }else{
             [self showlog:[NSString stringWithFormat:@"激励第%d循环加载失败",_currentlyRecycleRequestRewardVideoTimes]];
      }
    [[KKAnalytics shareManager]logTKEvent:REWARD_FAILED params:@{ERROR:error,LOAD_TIMES:@(_requestRewardVideoTimes),RECYCLE_TIME:@(_currentlyRecycleRequestRewardVideoTimes)}];
      _currentlyRecycleRequestRewardVideoTimes++;
    [self.delegate onAdsListener:REWARD_FAILED];
}
- (void)onRewardVideoTrigger {
    [self showlog:@"激励广告触发"];
    [[KKAnalytics shareManager]logTKEvent:REWARD_SHOW params:nil];
}
- (void)onRewardVideoPlayFailed:(nonnull NSString *)error {
    if(error){
        NSLog(@"激励广告播放失败%@",error);
         [[KKAnalytics shareManager]logTKEvent:REWARD_PLAY_ERROR params:@{ERROR:error,LOAD_TIMES:@(_requestRewardVideoTimes)}];
    }
}
- (void)onRewardVideoOpen {
    [self showlog:@"激励广告打开"];
    [[KKAnalytics shareManager]logTKEvent:REWARD_OPEN params:nil];
    [self.delegate onAdsListener:REWARD_OPEN];
}
- (void)onRewardVideoClick {
     [self showlog:@"激励广告点击"];
     [[KKAnalytics shareManager]logTKEvent:REWARD_CLICK params:nil];
     [self.delegate onAdsListener:REWARD_CLICK];
}
- (void)onRewardVideoClose {
     [self showlog:@"激励广告中途关闭"];
     [[KKAnalytics shareManager]logTKEvent:REWARD_CLOSE params:nil];
     [self.delegate onAdsListener:REWARD_CLOSE];
}


- (void)onRewardVideoComplete {
     [self showlog:@"激励广告完成"];
     if([_adsConfig objectForKey:@"re_im"]){
         [[KKAnalytics shareManager]logAdjustEvent:[_adsConfig objectForKey:@"re_im"]];
     }else{
         NSLog(@"===== ADJUST ERROR================请在AdsConfig中设置re_im激励展示打点Token");
     }
     [[KKAnalytics shareManager]logTKEvent:REWARD_IM params:nil];
     [self.delegate onAdsListener:REWARD_COMPLETE];
}

#pragma mark   banner

- (void)showBanner:(UIViewController *)rootViewController bannerContainer:(UIView *)containner isTop:(BOOL)position{
    if(_baseController)
        [_baseController showBanner:rootViewController bannerContainner:containner isTop:position];
}

- (void)showBanner:(UIViewController *)rootViewController bannerContainner:(UIView *)containner onImpressionEvent:(void (^)(void))onImpression{
    if(_baseController)
        [_baseController showBanner:rootViewController bannerUIContainer:containner onImpressionEvent:onImpression];
}
- (void)hideBanner{
    if(_baseController)
        [_baseController hideBanner];
}
- (void)onBannerRequest{
    [self showlog:@"请求banner广告"];
    
}
- (void)onBannerLoaded{
    [self showlog:@"banner加载成功"];
    
    [[KKAnalytics shareManager]logTKEvent:BANNER_LOADED params:nil];
}
- (void)onBannerImpression{
    [self showlog:@"banner展示成功"];
    if([_adsConfig objectForKey:@"ba_im"]){
        [[KKAnalytics shareManager]logAdjustEvent:[_adsConfig objectForKey:@"ba_im"]];
    }else{
        NSLog(@"===== ADJUST ERROR================请在AdsConfig中设置ba_im展示打点Token");
    }
     [self.delegate onAdsListener:BANNER_IM];
     [[KKAnalytics shareManager]logTKEvent:BANNER_IM params:nil];
}
- (void)onBanenrLoadedFailed:(NSString *)error{
     NSLog(@"Banner广告加载失败%@",error);
    [[KKAnalytics shareManager]logTKEvent:BANNER_FAILED params:@{ERROR:error}];
}
- (void)onBannerClick{
    [self showlog:@"Banner广告进行点击"];
    [[KKAnalytics shareManager]logTKEvent:BANNER_CLICK params:nil];
     [self.delegate onAdsListener:BANNER_CLICK];
}


- (void)onSplashRequest{
    [self showlog:@"请求开屏广告"];
    [self.delegate onAdsListener:SPLASH_REQUEST];
    [[KKAnalytics shareManager]logTKEvent:SPLASH_REQUEST params:nil];
}
- (void)onSplashLoaded{
      [self showlog:@"开屏广告加载成功"];
    [self.delegate onAdsListener:SPLASH_LOADED];
    [[KKAnalytics shareManager]logTKEvent:SPLASH_LOADED params:nil];
}
- (void)onSplashImpression{
    [self showlog:@"开屏广告展示成功"];
    if([_adsConfig objectForKey:@"sp_im"]){
        [[KKAnalytics shareManager]logAdjustEvent:[_adsConfig objectForKey:@"sp_im"]];
    }else{
        NSLog(@"===== ADJUST ERROR================请在AdsConfig中设置sp_im开屏打点Token");
    }
    [self.delegate onAdsListener:SPLASH_IMPRESSION];
    [[KKAnalytics shareManager]logTKEvent:SPLASH_IMPRESSION params:nil];
}
- (void)onSplashLoadedFailed:(NSString *)error{
    [self showlog:[NSString stringWithFormat:@"开屏广告加载失败%@",error]];
    [self.delegate onAdsListener:SPLASH_FAILED];
    [[KKAnalytics shareManager]logTKEvent:SPLASH_FAILED params:@{ERROR:error}];
}
@end
